<template>
  <div>
    <header-component></header-component>
    <div class="rab_yushou">
      <p class="rab_yushou_title">{{$t('presell.presell')}}</p>
      <div class="rab_jindutiao">
        <span class="rab_jindutiao_yigou" v-bind:style="{width: raisePercent}">
          <i class="rab_jindutiao_baifenbi">{{raisePercent}}</i>
        </span>
        <p class="rab_jindu_pirce">
          <span class="fl">0</span>
          <span class="fr">30000</span>
        </p>
      </div>
      <div class="deadline-cont">
        <span>{{$t('carGame.deadline_title')}}</span>
        <span><span class="c-gold">{{cdData.days}}</span> {{$t('carGame.day')}} <span class="c-gold">{{cdData.hours}}</span> {{$t('carGame.hour')}} <span class="c-gold">{{cdData.minutes}}</span> {{$t('carGame.minute')}} <span class="c-gold">{{cdData.seconds}}</span> {{$t('carGame.second')}}</span>
      </div>
      <p class="rab_yushou_p1">{{$t('presell.total')}}：{{preSellData && preSellData.raiseeos}}</p>
      <p class="rab_yushou_p1">{{$t('presell.sold_total')}}：{{preSellData && preSellData.raiserab}}</p>
      <P class="rab_yushou_p3">{{$t('presell.exchange_ratio')}}<br>
        <span class="f-tar">1-20000EOS</span><span class="f-tal">1EOS:500RAB</span><br>
        <span class="f-tar">20001-30000EOS</span><span class="f-tal">1EOS:400RAB</span>
      </P>
      <!--<p class="rab_yushou_p2">剩余时间：56小时 56分钟 56秒</p>-->
      <!--<div>
        <p class="rab_yushou_gm">
          <span class="rab_yushou_goumai">{{$t('presell.want_buy')}}</span>
          <input type="number" v-bind:placeholder="$t('presell.placeholder')" v-model="buyNum" class="rab_yushou_input">
          <span class="rab_yushou_goumai">EOS</span>
        </p>
        <p class="rab_yushou_p3">{{$t('presell.buy_hint')}}</p>
        <div class="xiazhutc_btn mrb30p">
          <span @click="buyRab">{{$t('presell.sure')}}</span>
        </div>
      </div>-->
    </div>
    <footer-component></footer-component>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import headerComponent from '@/view/common/header'
import footerComponent from '@/view/common/footer'

export default {
  name: 'name',
  data () {
    return {
      preSellData: null,
      raisePercent: '0%', // 已募集百分比
      buyNum: 1,
      isBuying: false,
      cdData: {
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00'
      },
      rankCD: null
    }
  },
  components: {
    headerComponent,
    footerComponent
  },
  computed: {
    lang: function () {
      return this.$store.getters.getLang
    },
    account: function () {
      return this.$store.getters.getAccount
    },
    difTime () {
      return this.$store.getters.getDifTime
    }
  },
  watch: {
    difTime (val) {
      this.initCD(val)
    }
  },
  created () {
    this.getData()
    this.initCD(this.difTime)
  },
  methods: {
    ...mapActions([
      'setBalance'
    ]),
    async getData () {
      await this.$scatterJs.scatter.connect(this.$config.gameName)
      let eos = this.$scatterJs.scatter.eos(this.$config.network, this.$eosjs)
      eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'other',
        json: true
      }).then(res => {
        this.preSellData = res.rows[0]
        this.initRaiseData()
        console.log('table other:', this.preSellData)
      }).catch(e => {
        console.log('other table e:', e)
      })
    },
    initRaiseData () {
      var total = this.$config.raiseTotal
      var curRaiseNum = parseFloat(this.preSellData.raiseeos)
      var percent = (100 * (curRaiseNum / total)).toFixed(2)
      this.raisePercent = percent + '%'
      console.log('percent: ', percent)
    },
    buyRab () {
      if (!this.preSellData.isopen) {
        this.$message({message: this.$t('presell.presell_stop')})
        return
      }
      if (this.isBuying) return
      if (!this.account) {
        this.$message({message: this.$t('presell.login_first')})
        return
      }
      var tempNum = this.buyNum
      console.log(tempNum)
      if (isNaN(tempNum) || tempNum <= 0 || tempNum % 1 !== 0) {
        this.$message({message: this.$t('presell.input_useful_num'), type: 'warning'})
        this.buyNum = 1
        return
      }
      var total = this.$config.raiseTotal - parseFloat(this.preSellData.raiseeos)
      if (tempNum > total) {
        this.$message({message: this.$t('presell.max_buy_num') + total, type: 'warning'})
        this.buyNum = total
        return
      }
      this.buyAction(tempNum)
      this.isBuying = true
    },
    async buyAction (num) {
      num = num * 1
      var buyNum = num.toFixed(4) + ' EOS'
      if (!this.eos) {
        await this.$scatterJs.scatter.connect(this.$config.gameName)
        this.eos = this.$scatterJs.scatter.eos(this.$config.write_network, this.$eosjs)
      }
      var memo = 't1'
      var inviter = localStorage.getItem('rab_ivt') || ''
      if (inviter) {
        memo = memo + '-' + inviter
      }
      this.eos.transfer(this.account.name, this.$config.cont_owner, buyNum, memo, true).then(res => {
        console.log('buy suc: ', res)
        this.$message({message: this.$t('presell.buy_suc'), type: 'success'})
        setTimeout(() => {
          this.isBuying = false
          setTimeout(() => {
            this.getData()
            this.getMyBalance(this.account.name)
          }, 2000)
        }, 1000)
      }).catch(err => {
        console.log('buy err: ', err)
        // var errText = this.$utils.getErrorMsg(err)
        // var errText = this.$t('errorCode:' + err.message) || ''
        var eCode = this.$utils.getErrorCode(err)
        var errText
        if (eCode) {
          errText = this.$t('errCode.' + eCode)
        } else {
          errText = this.$t('presell.buy_fail')
        }
        this.$message({message: errText, type: 'error'})
        setTimeout(() => {
          this.isBuying = false
        }, 1000)
      })
    },
    getMyBalance (name) {
      if (!name) {
        return
      }
      console.log('name = ', name)
      var tempBalance = {
        rab: '0.0000 RAB',
        eos: '0.0000 EOS'
      }
      // 获取我的RAB余额
      this.eos.getCurrencyBalance({code: this.$config.token_issuer, account: name, symbol: 'RAB'}).then(res => {
        console.log('RAB info: ', res)
        if (res.length === 0) {
          tempBalance.rab = '0.0000 RAB'
        } else {
          tempBalance.rab = res[0]
        }
      }).catch(e => {
        console.log('get RAB err: ', e)
      })
      this.eos.getCurrencyBalance({code: 'eosio.token', account: name, symbol: 'EOS'}).then(res => {
        console.log('EOS info: ', res)
        if (res.length === 0) {
          tempBalance.eos = '0.0000 EOS'
        } else {
          tempBalance.eos = res[0]
        }
      }).catch(e => {
        console.log('get RAB err: ', e)
      })
      this.setBalance(tempBalance)
    },
    initCD (difTime) {
      if (difTime) {
        this.clearRankCD()
        this.rankCD = setInterval(() => {
          this.calcCDdata(difTime)
        }, 1000)
        this.calcCDdata(difTime)
      }
    },
    clearRankCD () {
      if (this.rankCD) {
        clearInterval(this.rankCD)
        this.rankCD = null
      }
    },
    calcCDdata (difTime) {
      var endTime = this.$config.preSellTimestamp * 1000
      var curServiceTime = new Date().getTime() - difTime
      if (curServiceTime >= endTime) {
        this.cdData.days = '00'
        this.cdData.hours = '00'
        this.cdData.minutes = '00'
        this.cdData.seconds = '00'
        this.clearRankCD()
      } else {
        var remainTime = (endTime - curServiceTime) / 1000
        var days = parseInt(remainTime / (3600 * 24))
        var hours = parseInt((remainTime % (3600 * 24)) / 3600)
        var minutes = parseInt((remainTime % 3600) / 60)
        var seconds = parseInt(remainTime % 60)
        this.cdData.days = days >= 10 ? days : '0' + days
        this.cdData.hours = hours >= 10 ? hours : '0' + hours
        this.cdData.minutes = minutes >= 10 ? minutes : '0' + minutes
        this.cdData.seconds = seconds >= 10 ? seconds : '0' + seconds
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .rab_jindutiao {
    margin-bottom: 35px !important;
  }
  .deadline-cont {
    text-align: center;
    color: #fff;
    font-size: 16px;
    margin-bottom: 5px;
  }
  .c-gold {
    color: #e7b425;
  }
</style>
